﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Torch_Common.Helpes;
using Torch_IServices;

namespace Torch_WebApp.Controllers.PublicLogin
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private IUsersService _user;
        private IRolesService _role;
        public LoginController(IUsersService user, IRolesService role)
        {
            _user = user;
            _role = role;
        }

        [HttpPost]
        public async Task<IActionResult> Login(string account,string password) 
        {
            var data = await _user.LoginAsync(account,password);

            if (data != null) 
            {
                var roleTitle = await _role.QueryRoleTitleAsync(data.Rid);

                //将用户id和角色名作为单独的定义变量，封装进token字符串中。
                TokenModelJwt tokenModel = new TokenModelJwt { Uid = data.Id, Role = roleTitle };
                var jwtStr = JwtHelper.IssueJwt(tokenModel); //登录，获取到一定规则的Token令牌
                var suc = true;
                return Ok(new
                {
                    success = suc,
                    token = jwtStr,
                    role = roleTitle
                });
            }
            return BadRequest("你TM账号密码输错辣!!!");
        }

        [HttpPost]
        public async Task<IActionResult> a(string token) 
        {
            var getInfo = JwtHelper.SerializeJwt(token);
            return Ok(getInfo);
        }
    }
}
